<template>
    <div>
        <div v-show="ifHideDetail">
            <div class="operation">
                <span>部门</span>
                <select name="selectdept" class="input-sm" id="selectdept">
                </select>
                <span>起始日期</span>
                <input type="date" class="input-sm" name="selectdate" id="selectbegindate">
                <span>结束日期</span>
                <input type="date" name="selectdate" class="input-sm" id="selectenddate">
                <span for="">状态</span>
                <select name="selectcheckstatus" class="input-sm" id="selectcheckstatus">
                    <option value="2">全部</option>
                    <option value="0">未审核</option>
                    <option value="1">已审核</option>
                </select>
                <a style="margin-left:5px;" class="btn btn-theme btn-sm" @click="getPurchaseTable">查询</a>
                <a style="margin-left:5px;" class="btn btn-theme btn-sm" @click="calculate">请购统计</a>
            </div>
            <table class="table" id="purchaseTable"></table>
        </div>
        <div v-show="!ifHideDetail" style="background-color: #fff;padding: 5px;">
            <a style="float: left" class="btn btn-theme" @click="hidePurchasedetail"><i class="fa fa-reply"></i>&nbsp;返回</a>
            <h4 style="clear: both">请购详情</h4>
            <div style="float:left">
                <span>主题:{{currentPurchase.ftitle}}</span>
                <input type="text" style="border:0;background-color:transparent" readonly="readonly" id="title">
            </div>
            <div class="table-responsive" style="width: 100%">
                <table id="purchasedetail_table" class="table table-striped table-condensed table-bordered table-hover">
                    <thead>
                        <tr>
                            <th>请购单品编号</th>
                            <th>商品名</th>
                            <th>数量</th>
                            <th>单价</th>
                            <th>单品总价</th>
                            <th>使用部门</th>
                            <th>使用设备</th>
                            <th>备注</th>
                            <th>购买人</th>
                            <th>初审</th>
                            <th>初审人</th>
                            <th>初审日期</th>
                            <!--<th>初审备注</th>-->
                            <th>复审</th>
                            <th>复审人</th>
                            <th>复审日期</th>
                            <!--<th>复审备注</th>-->
                            </tr>
                            </thead>
                            <tbody id="result">
                                <tr v-for="(purchasedetail,index) in purchasedetails" >
                                    <td class="hidden">{{purchasedetail.fitemidno}}</td>
                                    <td>{{purchasedetail.fidno}}</td>
                                    <td>{{purchasedetail.fcgn}}</td> 
                                    <td>{{purchasedetail.fqty}}</td>  
                                    <td><a data-toggle="tooltip" data-placement="right" title="查看历史售价" @click="historyPrice(index)">{{purchasedetail.fprice}}</a></td>  
                                    <td>{{purchasedetail.fsum}}</td> 
                                    <td>{{purchasedetail.fusedeptname}}</td>
                                    <td>{{purchasedetail.fusedevice}}</td>
                                    <td>{{purchasedetail.fnotes}}</td> 
                                    <td>{{purchasedetail.fpurchaseusername}}</td>
                                    <td>
                                        <r-btn1 :index="index" v-if="purchasedetail.fyn1 === null"></r-btn1>
                                        <span v-else>{{purchasedetail.fyn1}}</span>
                                    </td>
                                    <td>{{purchasedetail.fynusername1}}</td>
                                    <td>{{purchasedetail.fyndate1}}</td>
                                    <td>
                                        <span v-if="purchasedetail.fyn2 === null && purchasedetail.fyn1 !== null "><r-btn2 :index="index" ></r-btn2></span>
                                        <span v-else-if="purchasedetail.fyn2 === null && purchasedetail.fyn1 === null ">等待初审</span>
                                        <span v-else-if="purchasedetail.fyn2 !== null && purchasedetail.fyn1 !== null ">{{purchasedetail.fyn2}}</span>    
                                    </td>
                                    <td>{{purchasedetail.fynusername2}}</td>
                                    <td>{{purchasedetail.fyndate2}}</td>
                                </tr>
                            </tbody>
                </table>
            </div>
            <div class="pull-left">
                <p style="float:left">商品总价:{{totalSum}}元</p>
                <p style="float:left;clear:both">说明:{{currentPurchase.fnotes}}</p>
            </div>
            <div style="clear: both"></div>
            <div class="modal fade" id="tips1" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
                <div class="modal-dialog" role="document">
                    <div class="modal-content container-fluid">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

                        </div>
                        <div class="modal-body row">
                            <span>提交审核？</span>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" id="stop" data-dismiss="modal">取消</button>
                            <button type="submit" class="btn btn-primary" @click="Submit1(currentPurchaseDetailId,text)">确定</button>
                        </div>
                    </div>
                </div>
            </div>
             <div class="modal fade" id="tips2" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
                <div class="modal-dialog" role="document">
                    <div class="modal-content container-fluid">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

                        </div>
                        <div class="modal-body row">
                            <span>提交审核？</span>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" id="stop" data-dismiss="modal">取消</button>
                            <button type="submit" class="btn btn-primary" @click="Submit2(currentPurchaseDetailId,text)">确定</button>
                        </div>
                    </div>
                </div>
            </div>
             <div class="modal fade" id="historyprice_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
                        <div class="modal-dialog" role="document">
                            <div class="modal-content container-fluid">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                    <h4 class="modal-title" id="exampleModalLabel">历史售价</h4>
                                </div>
                                <div class="modal-body row">
                                    <table id="historyprice_table" class="table table-striped table-bordered table-hover">

                                        <thead>
                                            <tr>
                                                <th>物料号</th>
                                                <th>物料编码</th>
                                                <th>物料名</th>
                                                <th>价格</th>
                                                <th>购买人</th>
                                                <th>购买日期</th>
                                            </tr>
                                        </thead>
                                        <tbody>

                                        </tbody>

                                    </table>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                                    <button type="submit" class="btn btn-primary" data-dismiss="modal">确定</button>
                                </div>
                            </div>
                        </div>
                    </div>
        </div>
    </div>
</template>
<script>
    import rBtn1 from './Review_Btn1'
    import rBtn2 from './Review_Btn2'

    import '../assets/js/jquery-jtemplates.js'
    export default {
        data() {
            return {
                ifHideDetail: true,
                currentPurchaseId: '',
                purchasedetails: '',
                currentPurchase: '',
                totalSum: 0,
                currentPurchaseDetailId: '',
                text: '',
                index: ''
            }
        },
        methods: {
            hidePurchasedetail() {
                this.ifHideDetail = true
            },
            getDept() {
                var _this = this
                $.ajax({
                    type: 'POST',
                    url: 'http://192.168.1.66:808/api/dept/fetchalllist',
                    data: {
                        'token': localStorage.token,
                        'userid': localStorage.userid,
                    },
                    dataType: 'json',
                    crossDomain: true,
                    async: false,
                    error: function(request) {
                        _this.$store.commit('showModal','连接错误');
                    },
                    success: function(retdata) {
                        var cont = '<option value="">全部</option>';
                        for (var i = 0; i < retdata.Table2.length; i++) {
                            cont += '<option value="' + retdata.Table2[i].fdname + '">' + retdata.Table2[i].fdname + '</option>';
                        }
                        $('#selectdept').html(cont);
                    }
                });
            },
            getPurchaseTable() {
                var _this = this
                $.ajax({
                    type: 'POST',
                    url: 'http://192.168.1.66:808/api/purchase/fetchlistbycondition',
                    data: {
                        'token': localStorage.token,
                        'userid': localStorage.userid,
                        'teamid': localStorage.activeteamid,
                        'yn': $('#selectcheckstatus').val(),
                        'deptname': $('#selectdept').val(),
                        'begindatetime': $('#selectbegindate').val().replace('/', '-'),
                        'enddatetime': $('#selectenddate').val().replace('/', '-'),
                        'extra.selectfield': '*',
                        'extra.sortfield': 'fidno',
                        'extra.pagesize': 99999999,
                        'extra.pageindex': 1,
                    },
                    dataType: 'json',
                    crossDomain: true,
                    error: function(request) {
                        _this.$store.commit('showModal','连接错误')
                    },
                    success: function(retdata) {
                        if (retdata.Table1[0].status == false) {
                            _this.$store.commit('showModal','未找到匹配的记录')
                            window.location.reload()
                        } else {
                            for (var i = 0; i < retdata.Table2.length; i++) {
                                // if (retdata.Table2[i].fnotes != null && retdata.Table2[i].fnotes != '-') {
                                //     retdata.Table2[i].fnotes = retdata.Table2[i].fnotes.substring(0, 10) + '......'
                                // }
                                retdata.Table2[i].fentdte = retdata.Table2[i].fentdte.substring(0, 10)
                            }
                        }
                        var operateEvents = {
                            'click a[name="purchase"]': function(elem, value, row, index) {
                                _this.currentPurchase = row
                                _this.ifHideDetail = false
                                _this.currentPurchaseId = row.fidno
                                _this.getPurchaseDetail()
                            }
                        }
                        $('#purchaseTable').bootstrapTable('destroy')
                        $('#purchaseTable').bootstrapTable({
                            columns: [{
                                field: 'fidno',
                                title: '请购序号',
                                halign: 'center'
                            }, {
                                field: 'ftitle',
                                title: '请购主题',
                                halign: 'center'
                            }, {
                                field: 'fnotes',
                                title: '备注',
                                halign: 'center',
                                titleTooltip: 'fnotes'
                            }, {
                                field: 'fweixiuidno',
                                title: '维修单号',
                                halign: 'center'
                            }, {
                                field: 'fdeptname',
                                title: '请购部门',
                                halign: 'center'
                            }, {
                                field: 'username',
                                title: '请购人',
                                halign: 'center'
                            }, {
                                field: 'fentdte',
                                title: '请购时间',
                                halign: 'center'
                            }, {
                                field: 'fstatus',
                                title: '状态',
                                halign: 'center'
                            }, {
                                field: 'operate',
                                title: '操作',
                                halign: 'center',
                                formatter: '<a class="btn btn-theme btn-xs" name="purchase">查看详细</a>',
                                events: operateEvents
                            }],
                            data: retdata.Table2,
                            pagination: true,
                            paginationLoop: true,
                            onlyInfoPagination: false,
                            striped: true,
                            sidePagination: 'client',
                            pageNumber: 1,
                            pageSize: 10,
                            pageList: [10, 25, 50, 100, 200, 500],
                            smartDisplay: true,
                            // selectItemName: '',
                            showHeader: true,
                            maintainSelected: true,
                            clickToSelect: true,
                            singleSelect: false,
                            checkboxHeader: true,
                        })
                    }
                });
            },
            getPurchaseDetail() {
                var _this = this
                $.ajax({
                    type: 'POST',
                    url: 'http://192.168.1.66:808/api/purchase/fetchdetailbyid2',
                    data: {
                        'token': localStorage.token,
                        'userid': localStorage.userid,
                        'fidno2': _this.currentPurchaseId
                    },
                    dataType: 'json',
                    crossDomain: true,
                    error: function(request) {
                        _this.$store.commit('showModal','连接错误')
                    },
                    success: function(retdata) {
                        for (var i = 0; i < retdata.Table2.length; i++) {
                            retdata.Table2[i].fyndate1 = retdata.Table2[i].fyndate1.substring(0, 10)
                            retdata.Table2[i].fyndate2 = retdata.Table2[i].fyndate2.substring(0, 10)
                        }
                        var data = retdata
                        _this.purchasedetails = data.Table2
                        _this.calculateTotalSum()
                    }
                });
            },
            calculateTotalSum() {
                var totalSum = 0
                for (var i = 0; i < this.purchasedetails.length; i++) {
                    totalSum += this.purchasedetails[i].fsum
                }
                this.totalSum = totalSum
            },
            pass1(index) {
                this.showTipModal1()
                console.log(index)
                this.currentPurchaseDetailId = index
                this.text = '通过'
            },
            reject1(index) {
                this.showTipModal1()
                console.log(index)
                this.currentPurchaseDetailId = index
                this.text = '驳回'
            },
            pass2(index) {
                this.showTipModal2()
                console.log(index)
                this.currentPurchaseDetailId = index
                this.text = '通过'
            },
            reject2(index) {
                this.showTipModal2()
                console.log(index)
                this.currentPurchaseDetailId = index
                this.text = '驳回'
            },
            showTipModal1() {
                $('#tips1').modal('show')
            },
            showTipModal2() {
                $('#tips2').modal('show')
            },
            Submit1(index, text) {
                var _this = this
                var mydate = this.getnowtime()

                $.ajax({
                    type: 'POST',
                    url: 'http://192.168.1.66:808/api/purchasedetail/update',
                    data: {
                        'token': localStorage.token,
                        'userid': localStorage.userid,
                        'fteamid': localStorage.activeteamid,
                        'fidno': _this.purchasedetails[index].fidno,
                        'fidno2': _this.purchasedetails[index].fidno2,
                        'fitemidno': _this.purchasedetails[index].fitemidno,
                        'fqty': _this.purchasedetails[index].fqty,
                        'fprice': _this.purchasedetails[index].fprice,
                        'fsum': _this.purchasedetails[index].fsum,
                        'fnotes': _this.purchasedetails[index].fnotes,
                        'fpurchaseuser': _this.purchasedetails[index].fpurchaseuser,
                        'fyn1': text,
                        'fynuser1': localStorage.userid,
                        'fyndate1': mydate,
                        'fnote1': _this.purchasedetails[index].fnote1,
                        'fyn2': _this.purchasedetails[index].fyn2,
                        'fynuser2': _this.purchasedetails[index].fynuser2,
                        'fyndate2': _this.purchasedetails[index].fyndate2,
                        'fnote2': _this.purchasedetails[index].fnote2,
                        'fusedept':_this.purchasedetails[index].fusedept,
                        'fusedevice':_this.purchasedetails[index].fusedevice
                    },
                    dataType: 'json',
                    async: true,
                    crossDomain: true,
                    error: function(request) {
                        //_this.$store.commit('showModal','连接错误')
                    },
                    success: function(retdata) {
                        //window.location.reload();
                        $('#tips1').modal('hide');
                        _this.getPurchaseDetail()
                    }
                });
            },
            Submit2(index, text) {
                var _this = this
                var mydate = this.getnowtime()

                $.ajax({
                    type: 'POST',
                    url: 'http://192.168.1.66:808/api/purchasedetail/update',
                    data: {
                        'token': localStorage.token,
                        'userid': localStorage.userid,
                        'fteamid': localStorage.activeteamid,
                        'fidno': _this.purchasedetails[index].fidno,
                        'fidno2': _this.purchasedetails[index].fidno2,
                        'fitemidno': _this.purchasedetails[index].fitemidno,
                        'fqty': _this.purchasedetails[index].fqty,
                        'fprice': _this.purchasedetails[index].fprice,
                        'fsum': _this.purchasedetails[index].fsum,
                        'fnotes': _this.purchasedetails[index].fnotes,
                        'fpurchaseuser': _this.purchasedetails[index].fpurchaseuser,
                        'fyn1': _this.purchasedetails[index].fyn1,
                        'fynuser1': _this.purchasedetails[index].fynuser1,
                        'fyndate1': _this.purchasedetails[index].fyndate1,
                        'fnote1': _this.purchasedetails[index].fnote1,
                        'fyn2': text,
                        'fynuser2': localStorage.userid,
                        'fyndate2': mydate,
                        'fnote2': _this.purchasedetails[index].fnote2,
                        'fusedept':_this.purchasedetails[index].fusedept,
                        'fusedevice':_this.purchasedetails[index].fusedevice
                    },
                    dataType: 'json',
                    async: true,
                    crossDomain: true,
                    error: function(request) {
                        //_this.$store.commit('showModal','连接错误')
                    },
                    success: function(retdata) {
                        //window.location.reload();
                        $('#tips2').modal('hide');
                        _this.getPurchaseDetail()
                    }
                });
            },
            padleft0(obj) {
                return obj.toString().replace(/^[0-9]{1}$/, "0" + obj);
            },
            getnowtime() {
                var nowtime = new Date();
                var year = nowtime.getFullYear();
                var month = this.padleft0(nowtime.getMonth() + 1);
                var day = this.padleft0(nowtime.getDate());
                var hour = this.padleft0(nowtime.getHours());
                var minute = this.padleft0(nowtime.getMinutes());
                var second = this.padleft0(nowtime.getSeconds());
                var millisecond = nowtime.getMilliseconds();
                millisecond = millisecond.toString().length == 1 ? "00" + millisecond : millisecond.toString().length == 2 ? "0" + millisecond : millisecond;
                return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second + "." + millisecond;
            },
            historyPrice(index) {
                $('#historyprice_modal').modal('show');
                var _this = this
                $.ajax({
                    url: 'http://192.168.1.66:808/api/purchasedetail/gethistoryprice',
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        'token': localStorage.token,
                        'userid': localStorage.userid,
                        'fidno': _this.purchasedetails[index].fitemidno
                    },
                    crossDomain: true,
                    async: 'true',
                    success: function(res) {
                        if (res.Table1.status == false) {
                            _this.$store.commit('showModal','无历史售价');
                        } else {
                            var tablecont = '';
                            for (var i = 0; i < res.Table2.length; i++) {
                                tablecont += '<tr><td>' + res.Table2[i].fidno + '</td><td>' + res.Table2[i].fitemno + '</td><td>' + res.Table2[i].fcgn + '</td><td>' + res.Table2[i].fprice + '</td><td>' + res.Table2[i].username + '</td><td>' + res.Table2[i].fentdte + '</td></tr>';
                            }
                            $('#historyprice_table tbody').html(tablecont);
                        }
                    }
                })
            },
            calculate() {
                var _this = this
                $.ajax({
                    type: 'POST',
                    url: 'http://192.168.1.66:808/api/purchase/fetchlistbycondition',
                    data: {
                        'token': localStorage.token,
                        'userid': localStorage.userid,
                        'teamid': localStorage.activeteamid,
                        'yn': $('#selectcheckstatus').val(),
                        'deptname': $('#selectdept').val(),
                        'begindatetime': $('#selectbegindate').val().replace('/', '-'),
                        'enddatetime': $('#selectenddate').val().replace('/', '-'),
                        'extra.selectfield': '*',
                        'extra.sortfield': 'fidno',
                        'extra.pagesize': 99999999,
                        'extra.pageindex': 1,
                    },
                    dataType: 'json',
                    crossDomain: true,
                    async: false,
                    error: function(request) {
                        _this.$store.commit('showModal','连接错误');
                    },
                    success: function(retdata) {
                        var purchase_list = [];
                        var purchasedetail_list = [];
                        var totalprice = 0;
                        var totalprice_pass = 0;
                        for (var i = 0; i < retdata.Table2.length; i++) {
                            purchase_list.push(retdata.Table2[i].fidno)
                        }
                        for (var i = 0; i < purchase_list.length; i++) {
                            $.ajax({
                                type: 'POST',
                                url: 'http://192.168.1.66:808/api/purchase/fetchdetailbyid2',
                                data: {
                                    token: localStorage.token,
                                    userid: localStorage.userid,
                                    'fidno2': purchase_list[i],
                                },
                                dataType: 'json',
                                async: false,
                                crossDomain: true,
                                error: function(request) {
                                    _this.$store.commit('showModal','连接错误');
                                },
                                success: function(retdata) {
                                    for (var j = 0; j < retdata.Table2.length; j++) {
                                        if (retdata.Table2[j].fyn2 == '通过') {
                                            totalprice_pass += retdata.Table2[j].fsum
                                        }
                                        totalprice += retdata.Table2[j].fsum
                                    }
                                }
                            });
                        }
                        _this.$store.commit('showModal',$('#selectbegindate').val().replace('/', '-') + '到' + $('#selectenddate').val().replace('/', '-') + $('#selectdept').val() + '共请购' + totalprice + '元，审核通过' + totalprice_pass + '元');
                       }
                });
            }
        },
        mounted() {
            this.getDept()
            this.getPurchaseTable()
        },
        components: {
            rBtn1,
            rBtn2
        }
    }
</script>
<style>
    th {
        text-align: center
    }
</style>